/**
 * ...
 * @author Franco Ponticelli
 */

package uform.ui.comp;
import thx.util.Message;
import uform.property.Property;
import uform.property.IProperty;
import uform.property.IReadProperty;
import uform.ui.comp.Component;
import uform.ui.comp.NamedComponent;
using Types;

class Control<T> extends NamedComponent
{
	public var value(default, null) : IProperty<T>;
	public var errors(default, null) : IProperty<Array<Message>>;
	public var required(default, null) : IProperty<Bool>;
	private function new(name : String, ?value : T)
	{
		super(name);
		this.required = new Property(true);
		this.value = new Property();
		if (null != value)
			this.value.set(value);
		this.errors = new Property([]);
	}
	
	override function _id() : String
	{
		return this.className().substr(0,1).toUpperCase();
	}
	
	override public function dispose()
	{
		value.onChange.clear();
		value = null;
		errors.onChange.clear();
		errors = null;
		required.onChange.clear();
		required = null;
		super.dispose();
	}
	
	public function addError(?message : Message, ?s : String, ?params : Array<Dynamic>) : Control<T>
	{
		if (null == message)
			message = new Message(s, params);
		var messages = errors.get();
		if (null == messages)
		{
			messages = [];
			errors.set(messages);
		}
		messages.push(message);
		return this;
	}
	
	public function resetErrors()
	{
		errors.set([]);
		return this;
	}
	
	public function hasErrors()
	{
		return errors.get().length > 0;
	}
}